package com.cos.hospital.tool;

import android.content.Context;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechRecognizer;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;


/**
 * @author YBY
 * @description 语音听写工具类
 */
public class USpeech {
    private volatile static USpeech instance;
    // 语音听写对象
    private SpeechRecognizer speechRecognizer;

    private USpeech() {
    }

    public static USpeech getInstance() {
        if (instance == null) {
            synchronized (USpeech.class) {
                if (instance == null) {
                    instance = new USpeech();
                }
            }
        }
        return instance;
    }

    public void init(Context context) {
        if (speechRecognizer == null) {
            speechRecognizer = SpeechRecognizer.createRecognizer(context, code -> {
                if (code != ErrorCode.SUCCESS) {
                    USnackbar.showError(context, "初始化失败，错误码：" + code);
                    instance = null;
                }
            });
        }
    }

    public void startListening(RecognizerListener recognizerListener) {
        if (speechRecognizer != null) {
            speechRecognizer.startListening(recognizerListener);
        }
    }

    public void cancel() {
        if (speechRecognizer != null) {
            speechRecognizer.cancel();
        }
    }

    public void stopListening() {
        if (speechRecognizer != null) {
            speechRecognizer.stopListening();
        }
    }

    public String parseIatResult(RecognizerResult recognizerResult) {
        if (recognizerResult == null) {
            return null;
        }
        String resultString = recognizerResult.getResultString();
        if (resultString == null) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        try {
            JSONTokener tokener = new JSONTokener(resultString);
            JSONObject joResult = new JSONObject(tokener);

            JSONArray words = joResult.getJSONArray("ws");
            for (int i = 0; i < words.length(); i++) {
                // 转写结果词，默认使用第一个结果
                JSONArray items = words.getJSONObject(i).getJSONArray("cw");
                JSONObject obj = items.getJSONObject(0);
                stringBuilder.append(obj.getString("w"));
//				如果需要多候选结果，解析数组其他字段
//				for(int j = 0; j < items.length(); j++)
//				{
//					JSONObject obj = items.getJSONObject(j);
//					stringBuilder.append(obj.getString("w"));
//				}
            }
        } catch (Exception e) {
            ULog.d(e.toString());
        }
        return stringBuilder.toString();
    }

}